import messageManager from "../../managers/message.manager";
import { Bundle } from "../bundle/bundle";

/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-04-12 14:20:13
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2024-08-05 18:09:59
 * @FilePath: \dwys_web\extensions\phoenix-plugin-client\assets\core\net\webSocketClient\webSocketClient.ts
 * @Description: 
 */
export class WebSocketClient {
    private _ws: WebSocket;
    private _sendFailedBuldle: Array<Bundle>;
    private _verifyID = 0;

    constructor(host: string, port: number) {
        this._ws = new WebSocket("ws://" + host + ":" + port);
        this._ws.onopen = this.onOpen.bind(this);
        this._ws.onmessage = this.onMessage.bind(this);
        this._ws.onerror = this.onError.bind(this);
        this._ws.onclose = this.onClose.bind(this);
        this._ws.binaryType = "arraybuffer";
        this._sendFailedBuldle = new Array<Bundle>();
        this._verifyID = 0;
    }

    private onOpen(event: Event) {
        console.log('WebSocket connected:', event);
        // 可以在这里添加连接成功后的回调函数或通知
      }
    
      private onMessage(event: MessageEvent<ArrayBuffer>) {
        // const data = JSON.parse(event.data); // 假设服务器发送的是JSON格式数据
        // console.log('Received message:', data);
        // 可以在这里解析并处理接收到的消息
        messageManager.onMessage(new Uint8Array(event.data));
      }
    
      private onError(error: Event | Error) {
        console.error('WebSocket error:', error);
        // 可以在这里添加错误处理逻辑
      }
    
      private onClose(event: CloseEvent) {
        console.log('WebSocket closed:', event);
        // 可以在这里添加断开连接后的回调函数或通知
      }
      
      public sendBundle(bundle: Bundle) : boolean{
        if (this._ws.readyState === WebSocket.OPEN) {
          let re = bundle.finishData(this._verifyID);
          this._verifyID = re.vid;
          this._ws.send(bundle.getData().buffer);
          return re.isClear;
        } else {
          console.warn('WebSocket is not open, cannot send message.');
          this._sendFailedBuldle.push(bundle);
        }
        return false;
      }

      public send(data: Uint8Array) {
        if (this._ws.readyState === WebSocket.OPEN) {
          this._ws.send(data.buffer); // 假设发送的是JSON格式数据
        } else {
          console.warn('WebSocket is not open, cannot send message.');
        }
      }
    
      public close() {
        this._ws.close();
      }
}